package com.chinasoft.goodsManager.servlet;

import com.alibaba.fastjson.JSON;
import com.chinasoft.goodsManager.domain.Manager;
import com.chinasoft.goodsManager.service.LoginService;
import com.chinasoft.goodsManager.service.impl.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    //创建service对象
    LoginService loginService = new LoginServiceImpl();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求字符集编码，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获取表单信息
        String verify = request.getParameter("verify");
        String musernameOrMemail = request.getParameter("username");
        String mpassword = request.getParameter("password");
        //登录次数实现
        HttpSession session = request.getSession();
        Integer index = (Integer) session.getAttribute("index");
        String cap = String.valueOf(session.getAttribute("cap"));
        if (index==null){
            session.setAttribute("index",0);
            index = (Integer) session.getAttribute("index");
        }
        int[] arr = {1,index};
        String str = "";
        if (index<3){
            if (validateLogon(session, index, musernameOrMemail, mpassword)) {
                str = JSON.toJSONString(arr);
                response.getWriter().write(str);
            }else {
                arr[0] = 0;
                str = JSON.toJSONString(arr);
                response.getWriter().write(str);
            }
        }else {
            if (verify.equals(cap)){
                if (validateLogon(session, index, musernameOrMemail, mpassword)) {
                    str = JSON.toJSONString(arr);
                    response.getWriter().write(str);
                }else {
                    arr[0] = 0;
                    str = JSON.toJSONString(arr);
                    response.getWriter().write(str);
                }
            }else {
                arr[0] = 0;
                str = JSON.toJSONString(arr);
                response.getWriter().write(str);
            }
        }
    }

    private boolean validateLogon(HttpSession session, Integer index ,String musernameOrMemail, String mpassword) {
        Manager manager = loginService.fandUsernameAndPassword(musernameOrMemail, mpassword);
        if (manager!=null){
            session.setAttribute("manager",manager);
            return true;
        }else {
            session.setAttribute("index",index+1);
            return false;
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
